from server_socket import *
from socket_wrapper import *

from threading import Thread
from config import *
from response_protocol import *
from db import DB
class Server(object):
    #服务器核心类

    def __init__(self):
        #创建套接字
        self.server_socket = ServerSocket()

        self.request_handle_function = {}
        self.register(REQUEST_LOGIN, self.request_login_handle)
        self.register(REQUEST_CHAT, self.request_chat_handle)

        self.clients = {}

        self.db = DB()

    def register(self, request_id, handle_function):
        #注册消息类型和处理函数到字典
        self.request_handle_function[request_id] = handle_function

    def startup(self):

        while True:
            #获取连接并提供服务
            soc, addr = self.server_socket.accept()

            #包装socket
            client_soc = SockerWrapper(soc)

            #收发消息
            t = Thread(target=self.request_handle, args=(client_soc, ))
            t.start()


    def request_handle(self, client_soc):
        while True:
            #接收客户端信息
            recv_data = client_soc.recv_data()

            if not recv_data:
                self.remove_offline_user(client_soc)
                client_soc.close()
                break

            #解析数据
            parse_data = self.parse_request_text(recv_data)

            # if parse_data['request_id'] == REQUEST_LOGIN:
            #     self.request_login_handle()
            # elif parse_data['request_id'] == REQUEST_CHAT:
            #     self.request_chat_handle()

            handle_function = self.request_handle_function.get(parse_data['request_id'])
            if handle_function:
                handle_function(client_soc, parse_data)

    def remove_offline_user(self, client_soc):
        print("有客户的下线")
        for username, info in self.clients.items():
            if info['sock'] == client_soc:
                print(self.clients)
                del self.clients[username]
                print(self.clients)
                break

        pass

    def parse_request_text(self, text):
        print("解析客户端数据：" + text)
        request_list = text.split(DELIMITER)

        #按照类型解析数据
        request_data = {}
        request_data['request_id'] = request_list[0]

        if request_data['request_id'] == REQUEST_LOGIN:
            request_data['username'] = request_list[1]
            request_data['password'] = request_list[2]
        elif request_data['request_id'] == REQUEST_CHAT:
            request_data['username'] = request_list[1]
            request_data['messages'] = request_list[2]

        return request_data

    def request_login_handle(self, client_soc, request_data):
        print('登录功能')

        #获取账号密码

        username = request_data['username']
        password = request_data['password']

        #检查是否可以登录

        res, nickname, username = self.check_user_login(username, password)

        #登陆成功保存当前用户信息
        if res == '1':
            self.clients[username] = {'sock':client_soc, 'nickname':nickname}

        #拼接返回客户端信息
        response_text = ResponseProtocol.response_login_result(res, nickname, username)

        #把消息发送给客户端
        client_soc.send_data(response_text)


    def request_chat_handle(self, client_soc, request_data):
        print('聊天功能:', request_data)

        username = request_data['username']
        message = request_data['messages']
        nickname = self.clients[username]['nickname']

        msg = ResponseProtocol.response_chat(nickname, message)

        for u_name, info in self.clients.items():
            if username == u_name:
                continue
            info['sock'].send_data(msg)

    def check_user_login(self, username, password):
        sql = "select * from user where user_name = '%s'"%username
        result = self.db.get_one(sql)

        if not result:
            return '0', '', username

        if password != result['user_password']:
            return '0', '', username

        return '1', result['user_nickname'], username

if __name__ == '__main__':
    Server().startup()